<template>
  <div class="app-container">
    <!-- 头部搜索区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="searchForm.reportNumber" placeholder="请输入报表编号" clearable />
        </el-col>
        <el-col :span="10">
          <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="YYYY-MM-DD" style="width: 100%" />
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option v-for="status in statusOptions" :key="status.dictValue" :label="status.dictLabel"
              :value="status.dictValue" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 报表表格区域 -->
    <el-card class="mt-2">
      <div class="table-header">
        <el-button type="primary" @click="showCreateDialog = true">新建报表</el-button>
        <!-- 导出 -->
        <el-button type="success" @click="handleExport" icon="Download">导出</el-button>

      </div>
      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="reportNumber" label="报表编号" align="center" />
        <el-table-column prop="reportName" label="报表名称" align="center" />
        <el-table-column prop="generationTime" label="填报时间" align="center" />
        <el-table-column prop="samplingPerson" label="填报人" align="center" />
        <el-table-column prop="reportStatus" label="状态" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.reportStatus)">
              {{ getStatusLabel(row.reportStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row.id)">查看详情</el-button>
            <!-- 编辑icon -->
            <el-button size="small" @click="buDiao(row)" v-if="row.reportStatus != '2'">数据调补</el-button>
            <el-button v-if="row.reportStatus != '2'" size="small" type="danger" @click="handleDelete(row.id)">
              删除
            </el-button>
            <el-button v-if="row.reportStatus == '1'||row.reportStatus == '0'" size="small" type="success" @click="tiJiao(row)">
              提交
            </el-button>
            <el-dropdown v-if="row.reportStatus === '1'" trigger="click" style="margin-left: 10px;">
              <el-button size="small">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleApprove(row.id)">审核通过</el-dropdown-item>
                  <el-dropdown-item @click="handleReject(row.id)">审核驳回</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :total="pagination.total" :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 新建报表对话框 -->
    <el-dialog v-model="showCreateDialog" title="新建水质化验报表" width="70%" @closed="resetCreateForm">
      <el-form ref="reportForm" :model="newReportForm" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="报表名称" prop="reportName">
              <el-input v-model="newReportForm.reportName" placeholder="请输入报表名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采样地点" prop="dataSources">
              <el-input v-model="newReportForm.dataSources" placeholder="请输入采样地点" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="采样时间" prop="generationTime">
              <el-date-picker v-model="newReportForm.generationTime" type="datetime" placeholder="选择采样时间"
                style="width: 100%" value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测人员" prop="samplingPerson">
              <el-input v-model="newReportForm.samplingPerson" placeholder="请输入检测人员姓名" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider />

        <h3>水质检测数据</h3>
        <el-table :data="newReportForm.reportItemForms" border style="width: 100%; margin-bottom: 20px">
          <el-table-column prop="itemName" label="检测项目" width="200">
            <template #default="{ $index }">
              <el-select v-model="newReportForm.reportItemForms[$index].itemName" placeholder="请选择检测项目"
                style="width: 100%">
                <el-option v-for="item in testItemOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="testValue" label="检测值">
            <template #default="{ $index }">
              <el-input v-model="newReportForm.reportItemForms[$index].testValue" placeholder="请输入检测值"
                @blur="validateTestValue($index)" />
            </template>
          </el-table-column>
          <el-table-column prop="unit" label="单位" width="120">
            <template #default="{ $index }">
              <el-input v-model="newReportForm.reportItemForms[$index].unit" placeholder="请输入检测值"
                @blur="validateTestValue($index)" />
            </template>
          </el-table-column>
          <el-table-column prop="standardValue" label="标准值" width="150">
            <template #default="{ $index }">
              <el-input v-model="newReportForm.reportItemForms[$index].standardValue" placeholder="请输入检测值"
                @blur="validateTestValue($index)" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" align="center">
            <template #default="{ $index }">
              <el-button type="danger" size="small" :icon="Delete" circle @click="removeTestItem($index)" />
            </template>
          </el-table-column>
        </el-table>

        <el-button type="primary" @click="addTestItem">+ 添加检测项目</el-button>

        <el-divider />

        <el-form-item label="备注信息">
          <el-input v-model="newReportForm.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="submitReport">提交报表</el-button>
      </template>
    </el-dialog>

    <!-- 报表详情对话框 -->
    <el-dialog v-model="showDetailDialog" :title="`水质化验报表详情 - ${currentReport.reportNumber}`" width="70%">
      <div class="detail-container">
        <h3>基本信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="报表编号">{{ currentReport.reportNumber }}</el-descriptions-item>
          <el-descriptions-item label="报表名称">{{ currentReport.reportName }}</el-descriptions-item>
          <el-descriptions-item label="采样地点">{{ currentReport.dataSources }}</el-descriptions-item>
          <el-descriptions-item label="采样时间">{{ currentReport.generationTime }}</el-descriptions-item>
          <el-descriptions-item label="检测人员">{{ currentReport.samplingPerson }}</el-descriptions-item>
          <el-descriptions-item label="填报人">{{ currentReport.samplingPerson }}</el-descriptions-item>
          <el-descriptions-item label="填报时间">{{ currentReport.generationTime }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(currentReport.reportStatus)">
              {{ getStatusLabel(currentReport.reportStatus) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <el-divider />

        <h3>水质检测数据</h3>
        <el-table :data="currentReport.reportItemForms" border style="width: 100%">
          <el-table-column prop="itemName" label="检测项目" width="200" />
          <el-table-column prop="testValue" label="检测值" />
          <el-table-column prop="unit" label="单位" width="120" />
          <el-table-column prop="standardValue" label="标准值" width="150" />
          <el-table-column label="结果判定" width="120">
            <template #default="{ row }">
              <el-tag :type="row.resultStatus === 1 ? 'success' : 'danger'">
                {{ row.resultStatus === 1 ? '合格' : '不合格' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>

        <el-divider />

        <h3>备注信息</h3>
        <el-input v-model="currentReport.remark" type="textarea" :rows="3" readonly />

        <el-divider v-if="currentReport.logs?.length" />

        <h3 v-if="currentReport.logs?.length">操作记录</h3>
        <el-timeline v-if="currentReport.logs?.length">
          <el-timeline-item v-for="(log, index) in currentReport.logs" :key="index" :timestamp="log.operationTime">
            {{ log.actionDescription }} - {{ log.operatorName }}
          </el-timeline-item>
        </el-timeline>
      </div>

      <template #footer>
        <el-button @click="showDetailDialog = false">关闭</el-button>
        <el-button v-if="currentReport.reportStatus == '1'" type="success" @click="handleApprove(currentReport.id)">
          审核通过
        </el-button>
        <el-button v-if="currentReport.reportStatus == '1'" type="warning" @click="handleReject(currentReport.id)">
          审核驳回
        </el-button>
      </template>
    </el-dialog>

    <!-- 审核驳回对话框 -->
    <el-dialog v-model="showRejectDialog" title="审核驳回" width="500px">
      <el-form :model="rejectForm" label-width="80px">
        <el-form-item label="驳回原因" prop="auditComment">
          <el-input v-model="rejectForm.auditComment" type="textarea" :rows="4" placeholder="请输入驳回原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showRejectDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmReject">确定</el-button>
      </template>
    </el-dialog>

    <!-- 数据补调 -->
    <el-dialog v-model="buDiaoDialog" title="数据补调" width="700px">
      <el-form :model="buDiaoForm" label-width="80px">
        <el-form-item label="报表名称" prop="reportName">
          <el-input v-model="buDiaoForm.reportName" type="text" placeholder="请输入报表名称" />
        </el-form-item>
        <el-form-item label="驳回原因" prop="content">
          <el-input v-model="buDiaoForm.content" type="textarea" :rows="4" placeholder="请输入数据补调的内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="buDiaoDialog = false">取消</el-button>
        <el-button type="primary" @click="buDiaoDialogSub">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, ArrowDown } from '@element-plus/icons-vue'
import {
  getStatusList,
  getWaterQualityReportList,
  getWaterQualityReportDetail,
  addWaterQualityReport,
  reviewReport,
  deleteReport,
  adjustReport,
  commitReport,
  getLaboratoryWorkOrderDemoList
} from '@/api/prod_operate/water/report'
const {proxy} = getCurrentInstance();


// 搜索表单
const searchForm = reactive({
  reportNumber: '',
  dateRange: [],
  status: '',
  samplingPerson: '',
  startTime: '',
  endTime: ''
})

const buDiaoForm = reactive({
  id: null,
  content: '',
  reportName: ''
})

// 状态选项
const statusOptions = ref([])

// 表格数据
const tableData = ref([])
const loading = ref(false)

const buDiaoDialog = ref(false);

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 新建报表表单
const newReportForm = reactive({
  reportName: '',
  dataSources: '',
  generationTime: '',
  samplingPerson: '',
  remark: '',
  reportItemForms: [
    { itemName: '', testValue: null, unit: '', standardValue: '', resultStatus: 1 }
  ]
})

// 审核驳回表单
const rejectForm = reactive({
  id: null,
  auditComment: ''
})

// 检测项目选项
const testItemOptions = [
  { label: 'pH值', value: 'pH值' },
  { label: '浊度', value: '浊度' },
  { label: '余氯', value: '余氯' },
  { label: '总大肠菌群', value: '总大肠菌群' },
  { label: '氨氮', value: '氨氮' },
  { label: '溶解氧', value: '溶解氧' },
  { label: 'COD', value: 'COD' },
  { label: 'BOD', value: 'BOD' },
  { label: '总磷', value: '总磷' },
  { label: '总氮', value: '总氮' }
]

// 标准范围配置
const standardRanges = {
  'pH值': { min: 6.5, max: 8.5, unit: '' },
  '浊度': { max: 1, unit: 'NTU' },
  '余氯': { min: 0.05, unit: 'mg/L' },
  '总大肠菌群': { max: 0, unit: 'CFU/10mL' },
  '氨氮': { max: 0.5, unit: 'mg/L' },
  '溶解氧': { min: 5, unit: 'mg/L' },
  'COD': { max: 30, unit: 'mg/L' },
  'BOD': { max: 10, unit: 'mg/L' },
  '总磷': { max: 0.5, unit: 'mg/L' },
  '总氮': { max: 1.0, unit: 'mg/L' }
}

// 当前查看的报表
const currentReport = ref({})

// 对话框显示状态
const showCreateDialog = ref(false)
const showDetailDialog = ref(false)
const showRejectDialog = ref(false)

// 表单引用
const reportForm = ref(null)

// 表单验证规则
const rules = reactive({
  reportName: [
    { required: true, message: '请输入报表名称', trigger: 'blur' }
  ],
  dataSources: [
    { required: true, message: '请输入采样地点', trigger: 'blur' }
  ],
  generationTime: [
    { required: true, message: '请选择采样时间', trigger: 'change' }
  ],
  samplingPerson: [
    { required: true, message: '请输入检测人员', trigger: 'blur' }
  ]
})


// 导出数据
async function handleExport() {
    try {
        proxy.download("/operation/web/operationWaterQualityTestReport/export",searchForm , `user_${new Date().getTime()}.xlsx`);
    } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败')
    }
}

// 获取标准范围文本
const getStandardRangeText = (itemName) => {
  const range = standardRanges[itemName]
  if (!range) return ''

  if (range.min !== undefined && range.max !== undefined) {
    return `${range.min}~${range.max}`
  } else if (range.max !== undefined) {
    return `≤${range.max}`
  } else if (range.min !== undefined) {
    return `≥${range.min}`
  }
  return ''
}

// 获取状态标签
const getStatusLabel = (status) => {
  const statusObj = statusOptions.value.find(item => item.dictValue === status)
  return statusObj ? statusObj.dictLabel : status
}

// 搜索处理
const handleSearch = () => {
  // 处理日期范围
  if (searchForm.dateRange && searchForm.dateRange.length === 2) {
    searchForm.startTime = searchForm.dateRange[0]
    searchForm.endTime = searchForm.dateRange[1]
  } else {
    searchForm.startTime = ''
    searchForm.endTime = ''
  }

  pagination.currentPage = 1
  fetchReports()
}

// 重置搜索
const resetSearch = () => {
  searchForm.reportNumber = ''
  searchForm.dateRange = []
  searchForm.status = ''
  searchForm.samplingPerson = ''
  searchForm.startTime = ''
  searchForm.endTime = ''
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchReports()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchReports()
}


// 补调
const buDiao = (row) => {
  buDiaoForm.id = row.id;
  buDiaoForm.reportName = row.reportName;
  buDiaoDialog.value = true;
}

const tiJiao = async (row) => {
  ElMessageBox.confirm('确定要提交报表吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await commitReport(row.id);
      ElMessage.success('成功')
    } catch (error) {
      ElMessage.error(error.message)
    }
  })
}
// 查看详情
const handleView = async (id) => {
  try {
    const { data } = await getWaterQualityReportDetail(id)
    currentReport.value = data
    showDetailDialog.value = true
  } catch (error) {
    ElMessage.error('获取报表详情失败')
  }
}

// 删除报表
const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除该报表吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteReport(id)
      ElMessage.success('报表删除成功')
      fetchReports()
    } catch (error) {
      ElMessage.error('报表删除失败')
    }
  }).catch(() => {
    // 取消操作
  })
}

// 审核通过
const handleApprove = async (id) => {
  ElMessageBox.confirm('确定要通过该报表的审核吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await reviewReport({
        id,
        auditResult: 2,
        auditComment: '审核通过'
      })
      ElMessage.success('报表审核通过')
      fetchReports()
      if (showDetailDialog.value) {
        const { data } = await getWaterQualityReportDetail(id)
        currentReport.value = data
      }
    } catch (error) {
      ElMessage.error('审核操作失败')
    }
  }).catch(() => {
    // 取消操作
  })
}

// 审核驳回
const handleReject = (id) => {
  rejectForm.id = id
  rejectForm.auditComment = ''
  showRejectDialog.value = true
}

const buDiaoDialogSub = async () => {
  try {
    if (!buDiaoForm.content) {
      ElMessage.error('请填写补调内容');
      return
    }
    await adjustReport(buDiaoForm);
    ElMessage.success('报表删除成功')
    buDiaoDialog.value = false
  } catch (error) {
    ElMessage.error('补调失败')
  }
}
// 确认驳回
const confirmReject = async () => {
  if (!rejectForm.auditComment) {
    ElMessage.warning('请输入驳回原因')
    return
  }

  try {
    await reviewReport({
      id: rejectForm.id,
      auditResult: 3,
      auditComment: rejectForm.auditComment
    })
    ElMessage.success('报表已驳回')
    showRejectDialog.value = false
    fetchReports()
    if (showDetailDialog.value) {
      const { data } = await getWaterQualityReportDetail(rejectForm.id)
      currentReport.value = data
    }
  } catch (error) {
    ElMessage.error('审核操作失败')
  }
}

// 添加检测项目
const addTestItem = () => {
  newReportForm.reportItemForms.push({
    itemName: '',
    testValue: null,
    unit: '',
    standardValue: '',
    resultStatus: 1
  })
}

// 移除检测项目
const removeTestItem = (index) => {
  if (newReportForm.reportItemForms.length > 1) {
    newReportForm.reportItemForms.splice(index, 1)
  } else {
    ElMessage.warning('至少需要保留一个检测项目')
  }
}

// 检测项目变化处理
const handleTestItemChange = (index) => {
  const item = newReportForm.reportItemForms[index].itemName
  if (item && standardRanges[item]) {
    const range = standardRanges[item]
    newReportForm.reportItemForms[index].unit = range.unit || ''
    newReportForm.reportItemForms[index].standardValue = getStandardRangeText(item)
  } else {
    newReportForm.reportItemForms[index].unit = ''
    newReportForm.reportItemForms[index].standardValue = ''
  }
}

// 验证检测值
const validateTestValue = (index) => {
  const testItem = newReportForm.reportItemForms[index]
  if (!testItem.itemName) {
    ElMessage.warning('请先选择检测项目')
    return
  }

  if (testItem.testValue === null || testItem.testValue === '') {
    ElMessage.warning('请输入检测值')
    return
  }

  const numericValue = parseFloat(testItem.testValue)
  if (isNaN(numericValue)) {
    ElMessage.warning('检测值必须是数字')
    return
  }

  const range = standardRanges[testItem.itemName]
  if (!range) {
    testItem.resultStatus = 1 // 没有标准范围默认合格
    return
  }

  if (range.min !== undefined && range.max !== undefined) {
    testItem.resultStatus = numericValue >= range.min && numericValue <= range.max ? 1 : 0
  } else if (range.max !== undefined) {
    testItem.resultStatus = numericValue <= range.max ? 1 : 0
  } else if (range.min !== undefined) {
    testItem.resultStatus = numericValue >= range.min ? 1 : 0
  } else {
    testItem.resultStatus = 1 // 没有标准范围默认合格
  }
}

// 提交报表
const submitReport = async () => {
  try {
    // 验证基础表单
    await reportForm.value.validate()

    // 验证检测项目
    for (const item of newReportForm.reportItemForms) {
      if (!item.itemName) {
        ElMessage.warning('请选择所有检测项目')
        return
      }
      if (item.testValue === null || item.testValue === '') {
        ElMessage.warning('请输入所有检测值')
        return
      }
    }

    // 提交表单
    await addWaterQualityReport(newReportForm)

    ElMessage.success('报表创建成功')
    showCreateDialog.value = false
    resetCreateForm()
    fetchReports()
  } catch (error) {
    if (error.response) {
      ElMessage.error(error.response.data.msg || '报表创建失败')
    } else if (!error.message.includes('validate')) {
      ElMessage.error(error.message)
    }
  }
}

// 重置新建表单
const resetCreateForm = () => {
  Object.assign(newReportForm, {
    reportName: '',
    dataSources: '',
    generationTime: '',
    samplingPerson: '',
    remark: '',
    reportItemForms: [
      { itemName: '', testValue: null, unit: '', standardValue: '', resultStatus: 1 }
    ]
  })
}

// 获取报表数据
const fetchReports = async () => {
  try {
    loading.value = true

    const params = {
      ...searchForm,
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    }

    const data = await getWaterQualityReportList(params)
    tableData.value = data.rows || []
    pagination.total = data.total || 0
  } catch (error) {
    ElMessage.error('获取报表列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 获取状态列表
const fetchStatusList = async () => {
  try {
    const { data } = await getStatusList()
    statusOptions.value = data || []
  } catch (error) {
    ElMessage.error('获取状态列表失败')
  }
}

// 根据状态获取标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case '2': // 已处理
      return 'success'
    case '1': // 待审核
      return 'warning'
    case '0': // 待处理
      return 'danger'
    default:
      return 'info'
  }
}

onMounted(() => {
  fetchStatusList()
  fetchReports()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.table-header {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-tag {
  margin-right: 5px;
}

/* 详情页样式 */
.detail-container {
  padding: 10px;
}

.detail-container h3 {
  margin: 20px 0 15px 0;
  color: #606266;
}

.mt-2 {
  margin-top: 20px;
}
</style>